<?php
/**
 * @Notes:【】
 * @User: zwc
 * @Date: 2022-04-30 16:17
 */

namespace Wechat\Controller;


use App\Constants\Talk\MessageEvent;
use App\Event\Ocean\OceanNavigateTo;
use App\Event\TalkConnectEvent;
use App\Event\TalkEvent;
use App\Middleware\ws\UserSocketAuthMiddleware;
use App\Repository\WebSocket\UsersData;
use App\Service\WebSocket\SocketClientService;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Middleware;
use Swoole\WebSocket\Frame;
use Swoole\Http\Request;
use Wechat\Event\WsMessageEvent;
use Wechat\Middleware\AuthMiddleware;


/**
 * @Middleware(AuthMiddleware::class)
 */
class UserController extends BaseController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{

    public function onMessage($server, Frame $frame): void
    {
        $frameData = $this->analysisFrameData($frame->data);

        event()->dispatch(new WsMessageEvent($frameData->getEvent(), $frameData->getUserId(),$frameData->getMessage()));
    }


    public function onClose($server, int $fd, int $reactorId): void
    {
        var_dump('closed');
        $res = $this->SocketClientService->unbind($fd);
    }

    /**
     * @Inject()
     * @var SocketClientService
     */
    protected $SocketClientService;


    public function onOpen($server, Request $request): void
    {
        //推送
        $server->push($request->fd, json_encode([
            "event" => "connect",
            "content" => [
                "ping_interval" => 20,
                "ping_timeout" => 20 * 3,
            ],
        ]));


        //绑定
        $userData = UsersData::get();

        $this->SocketClientService->bind($request->fd, $userData);

        event()->dispatch(new TalkConnectEvent($userData->getUid(), $userData->getFrom()));
//        event()->dispatch(new TalkEvent(TalkEventConstant::EVENT_LOGIN, [
//            'user_id' => $user_id,
//            'status'  => 1,
//        ]);
    }
}